/**
 * Created by YJH on 2018/6/5.
 */
import React, {Component} from 'react';
import {
    StyleSheet,
    View,
    TouchableOpacity,
    TextInput,
    ListView,
    DeviceEventEmitter,
    RefreshControl,
    Platform,
    StatusBar,
    ActivityIndicator,
    Text,
} from 'react-native';
import GlobalStyles from '../../../res/styles/GlobalStyles';
import LanguageDao, {FLAG_LAN} from '../../../js/expand/dao/LanguageDao';
import NavigationBarComponent from '../../page/NavigationBarComponent';
import NavigationBarUtil from '../../util/NavigationBarUtil';
import Toast, {DURATION} from 'react-native-easy-toast';
import FavoriteDao from '../../expand/dao/FavoriteDao';
import ProjectModulePopular from '../../module/ProjectModulePopular';
import  {FLAG_STORAGE} from '../../expand/dao/DataRespository';
import FavoriteUtil from '../../util/FavoriteUtil'
import RespositoryCell from '../../common/RespositoryCell';
import makeCancelable from '../../expand/dao/Cancelable';

const NAVIGATION_BAR_HEIGHT_ANDROID = 40;
const NAVIGATION_BAR_HEIGHT_IOS = 44;
const STATUS_BAR_HEIGHT = 20;
const URL = 'https://api.github.com/search/repositories?q=';
const SEARCH_STR = '&sort=stars';
export default class FavoritePage extends Component{
    constructor(props) {
        super(props);

        this.languageDao = new LanguageDao(FLAG_LAN.flagKey);
        this.favoriteDao = new FavoriteDao(FLAG_STORAGE.flag_popular);
        this.items = [];
        this.btnKeys = [];
        this.state = {
            searchButton: '搜索',
            searchTxt: '',
            isLoading: false,
            favoriteKeys: [],
            showBottomButton: false,
            dataSource: new ListView.DataSource({
                rowHasChanged: (r1, r2) => r1 !== r2
            }),
        }

    }

    /**
     * 功能：判断key是否存在keys里面
     * @param key
     * @param keys
     */
    checkedTheKeyIsExit(key, keys) {
        if (!keys)return false;
        for (let k of keys) {
            if (k.name.toLowerCase() === key.toLowerCase()) {
                this.toast.show(">>>>>true>>>>>>>", DURATION.LENGTH_SHORT);
                return true;
            }
        }

        this.toast.show(">>>>>false>>>>>>>", DURATION.LENGTH_SHORT);
        return false;
    }

    //使用同步的方式进行调用
    async initKeys() {
        this.btnKeys = await this.languageDao.fetch();
    }

    componentDidMount() {
        this.initKeys();
    }

    /** 更新 project item 的搜藏的状态*/
    flushFavoriteState() {
        let projectModules = [];
        for (let i = 0, l = this.items.length; i < l; i++) {
            projectModules.push(new ProjectModulePopular(this.items[i],
                FavoriteUtil.checkFavorite(this.items[i], this.state.favoriteKeys)))
        }

        this.setState({
            searchTxt: '',
            searchButton: '搜索',
            isLoading: false,
            dataSource: this.state.dataSource.cloneWithRows(projectModules),
        });
    }


    getFavoriteKey() {
        return this.favoriteDao.getFavorKeys()
            .then(keys => {
                let favorites = keys ? keys : [];
                this.setState({favoriteKeys: favorites});
                this.flushFavoriteState()
            })
            .catch(err => {
                this.flushFavoriteState();
            })
    }

    onLoadRefresh() {
        setTimeout(() => {
            this.loadData();
        }, 1500);
    }

    /**
     * 功能：搜索功能
     */
    loadData() {
        this.setState({
            isLoading: true,
        });

        this.cancel=makeCancelable(fetch(URL + this.state.searchTxt + SEARCH_STR));
        this.cancel.then(response => response.json())
            .then(responseData => {
                if (!this || !responseData || !responseData.items || responseData.items.length === 0) {
                    this.refs.toast.show('没有搜索结果啦..', DURATION.LENGTH_SHORT);
                    this.setState({
                        isLoading: false,
                        searchTxt: '',
                        searchButton: '搜索',
                    });
                    return;
                }
                this.items = responseData.items;
                this.getFavoriteKey();
                let isExit = this.checkedTheKeyIsExit(this.state.inputTxt, this.btnKeys);
                let isShow=!isExit;
                this.setState({
                    showBottomButton: isShow,
                })
            })
            .catch(err => {
                this.setState({
                    isLoading: false,
                    searchTxt: '',
                    searchButton: '搜索',
                });
            });

    }

    onFavoritePressed(item, isFavorite) {
        if (isFavorite)
            this.favoriteDao.savaFavoriteItem(item.id.toString(), JSON.stringify(item));
        else this.favoriteDao.removeFavoriteItem(item.id.toString())
    }

    /**
     * 功能：点击进行搜索
     */
    onSearch() {
        this.input.blur();
        if (this.state.searchButton === '搜索') {
            this.loadData();
        } else {
            this.cancel.cancel();//取消网络请求操作
            this.setState({
                isLoading: false,
            });
        }
        this.setState({
            searchButton: this.state.searchButton === '搜索' ? '取消' : '搜索',
        });
    }

    renderNavBar() {
        let backButton = NavigationBarUtil.getLeftButton(() => {
            this.input.blur();
            this.props.navigator.pop()
        });
        let rightButton = NavigationBarUtil.getRightButtonWord(() => this.onSearch(), this.state.searchButton);
        let inputView = <TextInput
            ref={input => this.input = input}
            onChangeText={txt => this.state.searchTxt = txt}
            underlineColorAndroid='transparent'
            autoFocus={true}
            style={{
                flex: 1,
                height: Platform.OS === 'ios' ? 38 : 38,
                borderWidth: 1,
                borderColor: 'white',
                backgroundColor: 'white',
                borderRadius: 4,
                color: 'black',
                margin: 6,
                paddingHorizontal: 5,
                opacity: 0.8,
                fontWeight: '500'
            }}/>;

        return <View
            style={{flexDirection: 'row', alignItems: 'center', justifyContent: 'center', backgroundColor: '#2196F3'}}>
            {backButton}
            {inputView}
            {rightButton}
        </View>

    }

    renderSeparator(sectionID, rowID, adjacentRowHighlighted) {
        return <View key={rowID} style={styles.item_line}>
        </View>
    }

    renderRow(projectModule) {
        return <RespositoryCell
            key={projectModule.item.id}
            projectModule={projectModule}
            onFavoritePressed={(item, isFavorite) => this.onFavoritePressed(item, isFavorite)}
            {...this.props}
        />
    }

    buttonAdd = () => {

    };

    render() {
        let statusBar = <View style={[styles.statusBar, this.props.statusBar]}>
            <StatusBar {...this.props.statusBar}/>
        </View>;

        //加载进度控件view
        let indicatorView = this.state.isLoading ? <ActivityIndicator animating={this.state.isLoading}/> : null;

        let bottomButton = this.state.showBottomButton ?
            <TouchableOpacity
                style={styles.btnBottom}
                onPress={this.buttonAdd}>
                <View
                    style={{justifyContent: 'center'}}>
                    <Text style={styles.btnTitle}>添加标签</Text>
                </View>
            </TouchableOpacity> : null;

        return (
            <View style={styles.container}>
                {statusBar}
                {this.renderNavBar()}

                <ListView
                    dataSource={this.state.dataSource}
                    renderRow={(data) => this.renderRow(data)}
                    renderSeparator={(sectionID, rowID, adjacentRowHighlighted) =>
                        this.renderSeparator(sectionID, rowID, adjacentRowHighlighted)}
                    enableEmptySections={true}
                    refreshControl={
                        <RefreshControl
                            refreshing={this.state.isLoading}
                            onRefresh={() => this.onLoadRefresh()}
                        />}
                />

                {indicatorView}
                {bottomButton}
                <Toast ref="toast"/>
            </View>
        )
    }

}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#FCFCFC',
    },
    statusBar: {
        height: Platform.OS === 'ios' ? STATUS_BAR_HEIGHT : 0,
    },
    btnBottom: {
        height: 40,
        left: 10,
        right: 10,
        backgroundColor: '#2196F3',
        borderWidth: 1,
        borderRadius: 5,
        borderColor: '#2196F3',
        alignItems: 'center',
        justifyContent: 'center',
        alignSelf: 'center',
        position: 'absolute',
        top: GlobalStyles.windowHeight - 80,
    },
    btnTitle: {
        fontWeight: '500',
        fontSize: 18,
        color: 'white'
    },
});